const net = require('net');

let clients = {}; // 客户端列表
const server = net.createServer(socket => {
    let key = socket.remoteAddress + socket.remotePost;
    clients[key] = {
        nickname: undefined,
        socket
    };
    socket.setEncoding('utf8');
    socket.write('欢迎来到tcp聊天室\r\n第一次输入的内容的将设置成你的昵称\r\n输入h获取使用方法\r\n');
    socket.on('data',data => {
        data = data.replace('\r\n','');
        let i = data.slice(0,1);
        switch(i) {
            case 'h':
                help(key);
            break;
            case '@':
                whisper(key,data);
            break;
            case 'l':
                list(socket);
            break;
            case 'n':
                editName(key,data);
            break;
            default:
                broadcast(key,data);
            break;
        }
    })
});

let help = k => {
    clients[k].socket.write(`
        使用方法：\r\n
        @nickname:msg 私聊给nickname信息\r\n
        l 列出聊天室里的人员\r\n
        n:newnickname 修改昵称\r\n
    `);
};

let whisper = (k,d) => {
    let a = d.split(':'),
        toU = a[0].slice(1), msg = a[1], 
        { nickname } = clients[k], toUser;
    for(let c in clients) {
        if(clients[c].nickname == toU) {
            toUser = clients[c];
            break;
        }
    };
    if(toUser) {
        toUser.socket.write(`${nickname}:${msg}\r\n`);
    }else {
        clients[k].socket.write('找不到用户或者改用户已经下线\r\n');
    }
};

let list = s => {
    let result = '在线用户列表:\r\n';
    for(let s in clients) {
        result += (clients[s].nickname + '\r\n');
    }

    s.write(result);
};

let editName = (k,d) => {
    let n = d.split(':')[1];
    clients[k].nickname = n;
    clients[k].socket.write('昵称修改成功，新昵称为' + n + '\r\n');
};

let broadcast = (k,d) => {
    let { nickname } = clients[k];
    if(nickname) {
        for(let c in clients) {
            if(clients.hasOwnProperty(c) && c != k) {
                clients[c].write(`${nickname}:${d}\r\n`);
            }
        }
    }else {
        editName(k,'d:' + d); 
    }
};

server.listen(3000,() => {
    console.log(`tcp 聊天室启动成功`);
});